<?php

namespace App\Http\Controllers\Administrator;

use Hash;
use App\Models\User;
use Illuminate\Http\Request;
use App\Handlers\UploadHandler;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Http\Requests\Administrator\UserRequest;


class UserController extends Controller
{
    public function edit(User $user)
    {
        $this->authorize('update', $user);

        return backend_view('user.edit', compact('user'));
    }

    public function update(UserRequest $request, UploadHandler $uploader, User $user)
    {
        $this->authorize('update', $user);

        $data = $request->only('name', 'email', 'avatar', 'introduction');
        $user->update($data);
        if ($user->type == 1) {
            $agent = $user->agent;
            if ($agent) {
                $agent->account = $request->account;
                $agent->account_address = $request->account_address;
                $agent->account_real_name = $request->account_real_name;
                $agent->save();
            }

        }

        return redirect()->route('user.edit', $user->id)->with('success', '资料更新成功！');
    }

    public function backendIps(User $user)
    {
        if (empty($user->id)) {
            $user = \Auth::user();
        }

        return view('backend.user.backend_ips', compact('user'));
    }

    public function backendIpsUpdate(Request $request, User $user)
    {
        $backendIps = $this->validate($request, [
                'backend_ips.*' => 'nullable|ip'
            ]
        );
        $backendIpsMax = config('administrator.backend_ips_max');
        if (count($backendIps) >= 1 && count($backendIps) <= $backendIpsMax) {
            $user->backend_ips = array_values(array_filter(array_unique($backendIps['backend_ips'])));
            $user->save();
        } elseif (count($backendIps) > $backendIpsMax) {
            return redirect()->route('administrator.user.backend_ips')->with('success', '后台IP绑定失败！最大绑定IP数不超过' . $backendIpsMax);
        }

        return redirect()->route('administrator.user.backend_ips')->with('success', '后台IP绑定成功！');

    }

    public function apiIps(User $user)
    {
        if (empty($user->id)) {
            $user = \Auth::user();
        }
        return view('backend.user.api_ips', compact('user'));

    }

    public function apiIpsUpdate(Request $request, User $user)
    {
        $apiIps = $this->validate($request, [
                'api_ips.*' => 'nullable|ip'
            ]
        );

        $apiIpsMax = config('administrator.api_ips_max');
        if (count($apiIps) >= 1 && count($apiIps) <= $apiIpsMax) {
            $user->api_ips = array_values(array_filter(array_unique($apiIps['api_ips'])));
            $user->save();
        } elseif (count($apiIps) > $apiIpsMax) {
            return redirect()->route('administrator.user.api_ips')->with('success', '接口IP绑定失败！最大绑定IP不超过' . $apiIpsMax);
        }

        return redirect()->route('administrator.user.api_ips')->with('success', '接口IP绑定成功！');

    }

    public function password(User $user)
    {
        $this->authorize('update', $user);
        return backend_view('user.password', compact('user'));
    }

    /**
     * 修改密码
     */
    public function showPasswordForm()
    {
        return backend_view('user.password');
    }

    /**
     * 更新密码
     *
     * @param Request $request
     * @param User $user
     * @return $this
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function passwordRequestForm(Request $request, User $user)
    {
        $this->authorize('update', $user);

        $this->passwordValidator($data = $request->all());

        if ($request->password == $request->old_password) {
            return redirect()->back()->withInput()->withErrors('新密码不可与原密码一致！');
        }

        if (!$this->confirmedOldPassword($user, $request->old_password)) {
            return redirect()->back()->withInput()->withErrors('原密码错误！');
        }

        $user->update(['password' => $request->password]);
        return redirect()->route('user.edit', $user->id)->with('success', '密码更新成功！');
    }

    /**
     * 更新密码验证
     *
     * @param $data
     */
    protected function passwordValidator($data)
    {
        Validator::make($data, [
            'old_password' => 'required|string|max:255',
            'password' => 'required|string|min:6|confirmed',
        ], [
                'password.min' => '新密码至少为6位',
                'password.confirmed' => '确认密码与新密码不一致.',
            ]
        )->validate();
    }

    /**
     * 检查原密码是否正确
     *
     * @param User $user
     * @param $old_password
     * @return mixed
     */
    protected function confirmedOldPassword(User $user, $old_password)
    {
        return Hash::check($old_password, $user->password);
    }

}
